<template>
  <div class="add">
    <div class="forbid-height" v-if="pageShow == true" @click="forbidHit"></div>

    <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="140px" class="demo-ruleForm">
      <el-form-item label="标签" prop="tabs" class="form-tabs">
        <div class="form-tabs">
          <div class="list" v-for="(item, index) in labelList" :key="index"
            :class="{ active: item.acitve == false ? false : true }" @click="tabsClick(item)">
            {{ item.welfareGoodClassifyName }}
          </div>
        </div>
      </el-form-item>

      <el-form-item label="商品分类" prop="cascader" class="form-item">
        <el-cascader v-model="ruleForm.cascader" :options="cascaderOptions" @change="handleChange" clearable
          :props="optionsProps"></el-cascader>
      </el-form-item>

      <el-form-item label="参考价格（元）" prop="price" class="form-virtual">
        <el-input v-model="ruleForm.price" placeholder="请输入参考价格（元）"></el-input>
      </el-form-item>

      <el-form-item label="打卡天数" prop="fate" class="form-virtual">
        <el-input v-model="ruleForm.fate" placeholder="请输入打卡天数"></el-input>
      </el-form-item>

      <el-form-item label="选择商品" prop="choice" class="form-stock">
        <div class="stock">
          <div class="adds" @click.stop="addsHit">+ 选择商品</div>
        </div>

        <div class="table">
          <el-table :data="tableData" border :header-cell-style="{
            color: '#333333',
            backgroundColor: '#f3f3f3',
            padding: 0,
          }">
            <el-table-column prop="" label="商品图片">
              <template slot-scope="scope">
                <img class="imgs" :src="scope.row.goodIcon" alt="" />
              </template>
            </el-table-column>
            <el-table-column prop="goodName" label="商品名称">
            </el-table-column>

            <el-table-column prop="" label="规格">
              <template slot-scope="scope">
                <el-tag v-if="scope.row.skuStr">
                  {{ scope.row.skuStr }}
                </el-tag>
              </template>
            </el-table-column>

            <el-table-column fixed="right" label="操作" width="200">
              <template slot-scope="scope">
                <div class="operation">
                  <div class="list" @click="deleteHit(scope.row)">删除</div>
                </div>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </el-form-item>

      <el-form-item v-if="pageShow == false">
        <div class="form-button">
          <div class="list" @click="addCancel">取消</div>
          <div class="list" @click="addSave('ruleForm')">保存</div>
        </div>
      </el-form-item>
    </el-form>

    <!--新增或者编辑-->
    <div class="add">
      <el-dialog title="选择商品" :visible.sync="addVisible" :before-close="addClose" width="75%">
        <div class="commodity">
          <div class="search">
            <div class="input">
              <el-input v-model="commonValue" placeholder="商品名称" clearable></el-input>
            </div>

            <div class="common-button" @click="searchHit">搜索</div>
            <div class="common-button" style="background: #999999" @click="replacementHit">
              重置
            </div>
          </div>

          <div class="lint"></div>

          <div class="table" v-loading="loading">
            <el-table ref="multipleTable" tooltip-effect="dark" @selection-change="handleSelectionChange"
              :data="tableDataAdd" style="width: 100%" :default-sort="{ prop: 'price0', order: 'descending' }" border
              :header-cell-style="{
                color: '#333333',
                backgroundColor: '#f3f3f3',
              }">
              <el-table-column type="selection" width="70" align="center">
              </el-table-column>
              <el-table-column prop="goodName" label="商品名称" width="300">
              </el-table-column>
              <el-table-column prop="" label="商品图">
                <template slot-scope="scope">
                  <img class="imgs" :src="scope.row.goodIcon" alt="" />
                </template>
              </el-table-column>
              <el-table-column prop="goodOneClassifyName" label="商品分类">
              </el-table-column>

              <el-table-column label="规格">
                <template slot-scope="scope">
                  <el-tag v-if="scope.row.skuStr">
                    {{ scope.row.skuStr }}
                  </el-tag>
                </template>
              </el-table-column>

              <el-table-column fixed="right" label="操作" width="200">
                <template slot-scope="scope">
                  <div class="operation" @click="skuHit(scope.row)">
                    <div class="list">选择规格</div>
                  </div>
                </template>
              </el-table-column>
            </el-table>

            <div class="pagination">
              <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" background
                layout="prev, pager, next" :total="tableDataAddTotal" :current-page="page">
              </el-pagination>
            </div>
          </div>
        </div>

        <div class="add-form">
          <div class="attachment">
            <div class="list" @click="addClose">取消</div>
            <div class="list" @click="addConfirm('ruleFormAdd')">保存</div>
          </div>
        </div>
      </el-dialog>
    </div>

    <!--新增规格-->
    <div class="add">
      <el-dialog title="选择商品规格" :visible.sync="skuVisible" :before-close="skuClose" width="60%">
        <div class="add-form">
          <div class="form-sku">
            <div class="list" v-for="(item, index) in skutwoList" :key="index" @click="addSkuTwoHit(item, index)">
              <div class="title" :class="{ 'title-active': index == skuTowNum }">
                {{ item.goodStockProperty }}
              </div>
            </div>
          </div>

          <div class="attachment">
            <div class="list" @click="skuClose">取消</div>
            <div class="list" @click="skuConfirm">确认选择</div>
          </div>
        </div>
      </el-dialog>
    </div>

    <!--删除弹出框-->
    <div class="delete">
      <el-dialog title="删除" :visible.sync="deleteVisible" :before-close="deleteClose">
        <div class="delete-title">是否确认删除？</div>
        <div class="delete-attachment">
          <div class="list" @click="deleteClose">取消</div>
          <div class="list" @click="deleteConfirm">确定</div>
        </div>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import {
  welfareClassifyGoodList,
  welfareGoodListId,
  welfareGoodListAdd,
} from "@/api/welfare";

import { saveCommodityList, saveCommodityListId } from "@/api/save";

var throttle = require("@/utils/throttle"); // 防抖

export default {
  data() {
    return {
      id: "",
      pageShow: false,
      ruleForm: {
        cascader: "",

        virtual: "",
        price: "",
        tabs: -1,

        choice: "",
        fate: "",
      },
      rules: {
        cascader: [
          { required: true, message: "请选择商品分类", trigger: "blur" },
        ],
        price: [
          { required: true, message: "请输入参考价格（元）", trigger: "blur" },
        ],
        tabs: [{ required: true, message: "请选择标签类型", trigger: "blur" }],
        choice: [
          { required: true, message: "请选择福利商品", trigger: "blur" },
        ],

        fate: [{ required: true, message: "请输入打卡天数", trigger: "blur" }],
      },
      cascaderOptions: [],
      //----------------

      tableData: [],
      tableDataTotal: 0,
      loading: false,
      detailsObj: {},
      //------------------------------------
      addVisible: false,
      commonValue: "",
      commonCascaderOptions: [],
      optionsProps: {
        value: "welfareGoodClassifyId",
        label: "welfareGoodClassifyName",
      },
      commonCascaderValue: "",
      commonCascaderIndex: 0,
      //-----------
      commonObj: {},
      deleteVisible: false,
      //-------------
      page: 1,
      limit: 10,
      tableDataAdd: [],
      tableDataAddTotal: 0,
      multipleSelection: [],
      //-------------------------------
      skuObj: {},
      skuVisible: false,
      skuOneList: [],
      skutwoList: [],
      skuTowNum: -1,
      skuTowObj: {},
      //-------------------------------------------------------
      labelList: [],
    };
  },
  created() {
    this.pageShow = this.$route.query.soucre == 1 ? true : false;

    this.welfareClassifyGoodListMet();
    this.welfareClassifyGoodListMet1();
    //--------------------------
  },
  methods: {
    forbidHit() {
      this.$message.error("当前详情页，禁止修改");
    },
    welfareClassifyGoodListMet() {
      let params = {
        welfareGoodClassifyType: 1,
        pageSize: 9999,
        pageNo: 1,
      };

      welfareClassifyGoodList(params).then((res) => {
        if (res.errorCode == null) {
          res.resultData.classifyList.forEach((item, index) => {
            item.acitve = false;
          });

          this.labelList = res.resultData.classifyList;

          if (this.$route.query.id) {
            this.id = this.$route.query.id;
            this.welfareGoodListIdMet();
          }
        }
      });
    },
    welfareClassifyGoodListMet1() {
      let params = {
        welfareGoodClassifyType: 0,
        pageSize: 9999,
        pageNo: 1,
      };

      welfareClassifyGoodList(params).then((res) => {
        if (res.errorCode == null) {
          res.resultData.classifyList.forEach((item, index) => {
            item.acitve = false;
          });

          this.cascaderOptions = res.resultData.classifyList;
        }
      });
    },
    welfareGoodListIdMet() {
      let params = this.id;

      welfareGoodListId(params).then((res) => {
        if (res.errorCode == null) {
          this.detailsObj = res.resultData;
          //--------标签
          this.ruleForm.cascader = res.resultData.welfareGoodClassifyId;
          this.ruleForm.price = Number(
            res.resultData.welfareGoodPrice / 100
          ).toFixed(2);
          this.ruleForm.fate = res.resultData.welfareGoodDay;

          if (res.resultData.welfareGoodLabelIdList.length > 0) {
            // 数组对象（A）
            let listValue = res.resultData.welfareGoodLabelIdList.map((str) =>
              Number(str)
            );
            const arrValues = listValue;

            // 直接修改原数组
            this.labelList.forEach((info) => {
              if (arrValues.includes(info.welfareGoodClassifyId)) {
                info.acitve = true;
              } else {
                info.acitve = false;
              }
            });
          } else {
            // 直接修改原数组
            this.labelList.forEach((info) => {
              info.acitve = true;
            });
          }

          this.saveCommodityListIdMet(res.resultData);
        }
      });
    },
    saveCommodityListIdMet(info) {
      let params = info.goodId;

      saveCommodityListId(params).then((res) => {
        if (res.errorCode == null) {
          if (res.resultData.goodStockList.length > 0) {
            res.resultData.goodStockList.forEach((item, index) => {
              if (item.goodStockId == info.goodStockId) {
                res.resultData.skuTowObj = item;
                this.skuTowObj = item
                res.resultData.skuStr = item.goodStockProperty;

                this.skuTowNum = index
              }
            });
          }

          let array = [
            {
              goodId: res.resultData.goodId,
              goodIcon: res.resultData.goodIcon,
              goodName: res.resultData.goodName,
              skuStr: res.resultData.skuStr,
              skuTowObj: res.resultData.skuTowObj,
              goodStockId: info.goodStockId
            },
          ];

          this.tableData = array;
        }
      });
    },

    //-----------
    searchHit() {
      this.loading = true;
      this.page = 1;
      this.saveCommodityListMet();
    },
    replacementHit() {
      this.commonValue = "";

      this.loading = true;
      this.page = 1;
      this.saveCommodityListMet();
    },
    saveCommodityListMet() {
      let params = {
        bannerId: "",
        goodName: this.commonValue,
        goodClassifyId: "",
        orderType: "", // 排序字段 0无 1销售价 2销售数量 3创建时间
        orderBy: "", // 排序类型 0正 1倒
        isStatus: 1,

        pageSize: this.limit,
        pageNo: this.page,
      };

      saveCommodityList(params).then((res) => {
        if (res.errorCode == null) {
          let array = [];

          res.resultData.goodList.forEach((item, index) => {
            item.retailPrice = Number(item.retailPrice / 100).toFixed(2);
            item.costPrice = Number(item.costPrice / 100).toFixed(2);
            if (this.detailsObj.goodId == item.goodId) {
              res.resultData.goodList[index].skuStr = this.detailsObj.goodStock
              res.resultData.goodList[index].skuTowObj = this.detailsObj
              res.resultData.goodList[index].goodStockId = this.detailsObj.goodStockId
              array = res.resultData.goodList[index];
            }
          });


          console.log('2222', array)

          this.tableDataAdd = res.resultData.goodList;
          this.tableDataAddTotal = res.resultData.totalNum;

          this.loading = false;
          this.addVisible = true;
          let row = array;

          this.$nextTick(() => {
            this.$refs.multipleTable.toggleRowSelection(row);
          });
        }
      });
    },

    //-------------------------------------------------------
    handleChange(value) {
      console.log(value);
      this.ruleForm.cascader = value[0]
    },

    //--------------------------------------
    handleSelectionChange(selectedRows) {
      if (selectedRows.length > 1) {
        this.$refs.multipleTable.clearSelection();
        this.$refs.multipleTable.toggleRowSelection(
          selectedRows[selectedRows.length - 1]
        );
      }

      this.multipleSelection = [selectedRows[selectedRows.length - 1]];

    },
    addsHit() {
      this.addRoaid = 0;
      this.saveCommodityListMet();
    },
    addClose() {
      this.addVisible = false;
    },
    addConfirm() {
      console.log('商品规格', this.multipleSelection)

      if (this.multipleSelection.length == 0) {
        this.$message.error('请先勾选该商品！')
        return
      }
      let shwo = false

      this.multipleSelection.forEach((item, index) => {
        if (item.skuStr && item.skuStr != undefined) {
          shwo = true
        } else {
          this.$message.error('请先添加该商品规格！')
        }
      })

      if (shwo == true) {
        this.tableData = this.multipleSelection;
        this.ruleForm.choice = 1;
        this.addVisible = false;
      }
    },
    deleteHit(item) {
      this.commonObj = item;
      this.deleteVisible = true;
    },
    deleteClose() {
      this.deleteVisible = false;
    },
    deleteConfirm() {
      let num = 0;

      this.tableData.forEach((item, index) => {
        if (item.goodId == this.commonObj.goodId) {
          num = index;
        }
      });

      this.tableData.splice(num, 1);

      this.deleteVisible = false;
    },
    //----------
    skuHit(item) {
      this.skuObj = item;

      let params = item.goodId;

      saveCommodityListId(params).then((res) => {
        if (res.errorCode == null) {
          res.resultData.goodPropertyOneList.forEach((obj, a) => {
            obj.goodPropertyTwoList.forEach((k, j) => {
              k.active = false;
            });
          });

          this.skuOneList = res.resultData.goodPropertyOneList;
          this.skutwoList = res.resultData.goodStockList;

          this.skuVisible = true;
        }
      });
    },
    //--------------
    addSkuTwoHit(item, index) {
      this.skuTowNum = index;
      this.skuTowObj = item;
    },
    skuClose() {
      this.skuVisible = false;
    },
    skuConfirm() {
      let skuStr = this.skuTowObj.goodStockProperty;

      this.tableDataAdd.forEach((item, index) => {
        if (item.goodId == this.skuObj.goodId) {
          item.skuStr = skuStr;
          item.skuTowObj = this.skuTowObj;
        }
      });

      this.tableDataAdd = JSON.parse(JSON.stringify(this.tableDataAdd));
      this.skuVisible = false;
    },
    //--------
    tabsClick(item) {
      this.labelList.forEach((info, index) => {
        if (item.welfareGoodClassifyId == info.welfareGoodClassifyId) {
          info.acitve = !info.acitve;
        }
      });
    },

    //----------
    addCancel() {
      this.$router.push({
        path: "/welfare/receive/receive-commodity",
      });
    },

    addSave: throttle.throttle(function (formName) {
      let welfareGoodLabelIdList = [];
      this.labelList.forEach((item, index) => {
        if (item.acitve == true) {
          welfareGoodLabelIdList.push(item.welfareGoodClassifyId);
        }
      });

      console.log('22322', this.tableData)
      if (this.tableData.length > 0) {
        this.ruleForm.choice = 1;
      }


      this.$refs[formName].validate((valid) => {
        if (valid) {
          let params = {
            welfareGoodId: this.id,
            welfareGoodClassifyId: this.ruleForm.cascader,

            welfareGoodLabelIdList: welfareGoodLabelIdList,
            welfareGoodPrice: Number(this.ruleForm.price * 100),
            welfareGoodDay: Number(this.ruleForm.fate),
            goodId: this.tableData[0].goodId,
            goodStockId: this.tableData[0].skuTowObj.goodStockId,
          };

          console.log('22222', params)

          welfareGoodListAdd(params).then((res) => {
            if (res.errorCode == null) {
              this.$message.success(
                this.id == "" ? "新增商品成功！" : "编辑商品成功！"
              );

              setTimeout(() => {
                this.$router.push({
                  path: "/welfare/receive/receive-commodity",
                });
              }, 1000);
            } else {
              this.$message.error(res.errorMessage);
            }
          });
        } else {
          return false;
        }
      });
    }, 3000),

    //---------
    handleSizeChange(val) {
      this.limit = val;
      this.loading = true;
      this.saveCommodityListMet();
    },
    handleCurrentChange(val) {
      this.page = val;
      this.loading = true;
      this.saveCommodityListMet();
    },
  },
};
</script>

<style lang="less" scoped>
@import url("@/assets/css/delete.less");

.add {
  width: 100%;
  position: relative;

  .forbid-height {
    width: 100%;
    height: 100%;
    position: absolute;
    z-index: 10;
    display: flex;
  }

  .demo-ruleForm {
    /deep/ .el-form-item__content {
      width: 64%;
      margin-left: 0 !important;
    }

    .form-item {
      width: 500px;
      display: flex;

      /deep/ .el-cascader {
        width: 100%;
      }
    }

    .form-banner {
      .banners {
        /deep/ .el-form-item__content {
          display: flex;
        }

        display: flex;

        .img {
          width: 100px;
          height: 100px;
          display: flex;
          align-items: center;
          justify-content: center;
          border: 1px solid #ccc;
          border-radius: 5px;
        }

        .imgs {
          width: 100px;
          height: 100px;
          display: flex;
          align-items: center;
          justify-content: center;
          border: 1px solid #ccc;
          margin-left: 10px;
          border-radius: 5px;
        }
      }

      .text {
        color: #999;
        margin-left: 120px;
      }
    }

    .form-virtual {
      width: 500px;

      /deep/ .el-form-item__content {
        display: flex;
      }

      .title {
        margin-left: 20px;
        color: #999;
      }
    }

    .form-tabs {
      display: flex;
      align-items: center;

      .list {
        padding: 0px 10px;
        box-sizing: border-box;
        background: #e0e0e0;
        color: #222;
        cursor: pointer;
        margin-right: 15px;
        border-radius: 4px;
      }

      .active {
        background: #4b89cd;
        color: #fff;
      }
    }

    .form-stock {
      /deep/ .el-form-item__content {
        width: 100%;
        margin-left: 0 !important;
      }

      /deep/ .el-form-item__error {
        margin-left: 140px;
      }

      .stock {
        width: 70%;
        display: flex;

        .adds {
          cursor: pointer;
          height: 38px;
          width: 100px;
          display: flex;
          align-items: center;
          justify-content: center;
          border: 1px dashed #ccc;
          color: #999;
        }
      }

      .table {
        margin-top: 10px;
        margin-left: 140px;
        width: 90%;

        .parallel {
          display: flex;
          flex-wrap: wrap;

          .tags {
            margin-right: 10px;
            height: 40px;
            display: flex;
            align-items: center;
          }
        }
      }
    }

    .form-button {
      margin-left: 140px;
      margin-top: 100px;
      display: flex;
      align-items: center;

      /deep/ .el-form-item__content {
        line-height: 0;
      }

      .list {
        background: #3da8f5;
        color: #fff;
        font-size: 16px;
        margin-right: 20px;
        border-radius: 5px;
        height: 35px;
        display: flex;
        align-items: center;
        justify-content: center;
        cursor: pointer;
        padding: 0 20px;
        box-sizing: border-box;
      }

      .list:first-child {
        background: #808080;
      }
    }
  }

  .add {
    /deep/ .el-dialog__header {
      text-align: left;
      font-weight: 600;
      border-bottom: 1px solid #ddd;
    }

    /deep/ .el-dialog__body {
      padding-bottom: 10px;
    }

    .commodity {
      .common {
        .header {
          width: 100%;
          display: flex;
          align-items: center;
          border-bottom: 1px solid #ccc;

          .list {
            width: 150px;
            height: 35px;
            background: #999999;
            display: flex;
            align-items: center;
            justify-content: center;
            color: #fff;
            cursor: pointer;
          }

          .active {
            background: #2a82e4;
          }
        }
      }

      .search {
        display: flex;
        align-items: center;

        .input {
          margin-right: 10px;

          /deep/ .el-input {
            width: 250px;
          }
        }

        .common-button {
          padding: 9px 20px;
          box-sizing: border-box;
          border-radius: 5px;
          background: #2a82e4;
          font-size: 14px;
          color: #fff;
          margin-left: 20px;
          cursor: pointer;
        }

        .common-button:last-child {
          background: #999999;
        }
      }

      .lint {
        margin: 10px 0;
        width: 100%;
        height: 1px;
        background: #ccc;
      }

      .table {}
    }

    .add-form {
      width: 100%;
      padding-bottom: 20px;

      .attachment {
        width: 100%;
        margin-top: 50px;
        display: flex;
        align-items: center;
        justify-content: center;

        .list {
          background: #3da8f5;
          color: #fff;
          font-size: 16px;
          margin-right: 50px;
          border-radius: 5px;
          width: 100px;
          height: 35px;
          display: flex;
          align-items: center;
          justify-content: center;
          cursor: pointer;
        }

        .list:first-child {
          background: #808080;
        }

        .list:last-child {
          margin-right: 0;
        }
      }

      .form-sku {
        display: flex;
        flex-wrap: wrap;

        .list {
          width: calc(100% / 5);

          .title {
            font-weight: 600;
            margin-bottom: 10px;
            padding: 5px 20px;
            box-sizing: border-box;
            border-radius: 4px;
            border: 1px solid #ddd;
            margin-right: 10px;
            cursor: pointer;
          }

          .title-active {
            border: 1px solid #2a82e4;
          }

          .parallel {
            display: flex;

            .array {
              padding: 5px 20px;
              box-sizing: border-box;
              border-radius: 4px;
              border: 1px solid #ddd;
              margin-right: 10px;
              cursor: pointer;
            }

            .array-active {
              border: 1px solid #2a82e4;
            }
          }
        }
      }
    }
  }
}
</style>